/**
 * 
 */
package org.t2.backstage.module.recharge;

import java.util.ArrayList;
import java.util.List;

import org.gaming.backstage.PageData;
import org.gaming.backstage.PageQuery;
import org.gaming.service.advice.ResponseResult;
import org.gaming.service.apidoc.annotation.ApiDocument;
import org.gaming.tool.SortUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.t2.backstage.module.gameserver.model.GameServer;
import org.t2.backstage.module.gameserver.service.GameServerService;
import org.t2.backstage.module.recharge.model.RechargeProductCfg;
import org.t2.backstage.module.recharge.service.RechargeProductCfgService;
import org.t2.backstage.util.T2HttpUtil;

import sh.t2.share.apiutil.GameApi;
import sh.t2.share.module.recharge.RechargeApiProtocol.RechargeCfgRequest;
import sh.t2.share.module.recharge.RechargeApiProtocol.RechargeCfgResponse;
import sh.t2.share.module.recharge.RechargeCfgForm;

/**
 * @author YY
 *
 */
@Controller
public class RechargeProductCfgController {

	@Autowired
	private RechargeProductCfgService rechargeProductCfgService;
	@Autowired
	private GameServerService gameServerService;
	
	@ApiDocument("请求游戏充值商品配置数据")
	@RequestMapping(value = "/rechargeProductCfg/data.auth")
	@ResponseBody
	public PageData<RechargeProductCfg> data(PageQuery query) {
		List<RechargeProductCfg> cfgs = rechargeProductCfgService.getEntityList(0);
		SortUtil.sortInt(cfgs, RechargeProductCfg::getId);
		
		PageData<RechargeProductCfg> pageData = new PageData<>();
		pageData.setData(cfgs);
		pageData.setCount(cfgs.size());
		return pageData;
	}
	
	@ApiDocument("更新游戏充值商品配置数据")
	@RequestMapping(value = "/rechargeProductCfg/refresh.auth")
	@ResponseBody
	public void refresh() {
		GameServer gameServer = gameServerService.randomRunning();
		
		ResponseResult<RechargeCfgResponse> responseResult = T2HttpUtil.jsonPost(gameServer, GameApi.rechargeProductCfgUpdate, new RechargeCfgRequest(), RechargeCfgResponse.class);
		RechargeCfgResponse response = responseResult.getData();
		
		List<RechargeProductCfg> insertList = new ArrayList<>();
		for(RechargeCfgForm form : response.rechargeCfgs) {
			RechargeProductCfg cfg = new RechargeProductCfg();
			cfg.setId(form.getId());
			cfg.setName(form.getName());
			cfg.setType(form.getType());
			cfg.setPrice(form.getPrice());
			cfg.setObtainNum(form.getObtainNum());
			insertList.add(cfg);
		}
		rechargeProductCfgService.deleteAll();
		rechargeProductCfgService.insertAll(insertList);
	}
}
